import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//a utility for processing cmd line options
public class OptionParser {
   private final Map<String, Option> options=new HashMap<String, Option>();

   public void addBooleanOption(char s, String f, boolean n) {
      options.put(f, new BooleanOption(s, f, n));
   }
   public void addIntegerOption(char s, String f, boolean n) {
      options.put(f, new IntegerOption(s, f, n));
   }
   public void addStringOption(char s, String f, boolean n) {
      options.put(f, new StringOption(s, f, n));
   }

   public Option getOption(String f) {
      return options.get(f);
   }
   



   public String getUsage() {
      final StringBuilder sb=new StringBuilder();
      for(String k: options.keySet()) {
         final Option o=options.get(k);
         if(!o.isNecessary) {
            sb.append('[');
         }
         sb.append('-').append(o.shortName).append(", ").append("--")
           .append(o.fullName);
         if(!o.isNecessary) {
            sb.append(']');
         }
         sb.append(' ');
      }
      return sb.toString();
   }

   public void parse(String[] args) {
      for(int i=0; i<args.length; i++) {
         String a=args[i];
         boolean isMatchFound=false;
         for(String k: options.keySet()) {
            final Option o=options.get(k);
            if(o.match(a)) {
               isMatchFound=true;
               o.parse(args[++i]);
            }
         }
         if(!isMatchFound) {
            throw new IllegalArgumentException("\""+a+"\"");
         }
      }
   }
   
   
   
   public static void main(String[] args) {
      for(int i=0; i<args.length; i++) System.out.println(args[i]);
      final OptionParser p=new OptionParser();
      p.addBooleanOption('c', "cafe", false);
      p.addIntegerOption('f', "from", false);
      p.addStringOption('n', "link", true);
      
      System.out.println(p.getUsage());
      
      p.parse(args);
      
      boolean b=(Boolean)p.getOption("cafe").getValue();
      int i=(Integer)p.getOption("from").getValue();
      String s=(String)p.getOption("link").getValue();
      
      System.out.println(b);
      System.out.println(i);
      System.out.println(s);
   }

}

